package test.lyj.model;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import android.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import json.CurveObj;

/**
 * 绘制曲线
 * @title 
 * @author ysy
 * @date 2011-12-1
 * @email 1234gogogo@sina.com.cn
 */
public class DrawCurveView extends View implements OnTouchListener{
	/**
	 * 曲线画笔，可以通过它设置颜色，粗细等等
	 */
	private Paint curvePaint;
	/**
	 * 坐标画笔，可以通过它设置颜色，粗细等等
	 */
	private Paint coordinatePaint;
	/**
	 * 曲线点值，可以通过它设置颜色，粗细等等
	 */
	private Paint curveTextPaint;
	/**
	 * 是否需要显示曲线点上的数值。
	 */
	private boolean showCurveText=false;
	/**
	 * x轴的坐标数组
	 */
	private float[] fx=null;
	/**
	 * y轴的坐标数组
	 */
	private float[] fy=null;
	private  float[] perXs=null,perYs=null;
	private String[] perXsText=null, perYsText=null;
	/**
	 * x轴最大长度
	 */
	private float maxXpx=300;
	/**
	 * y轴最大长度
	 */
	private float maxYpx=300;
	/**
	 * 屏幕长宽
	 */
	private int screenWidth,screenHeight;
	
	
	private static final float MINP = 0.25f;
    private static final float MAXP = 0.75f;
    
    private Bitmap  mBitmap;
//    private Canvas  mCanvas;
    private Path    mPath;
    private Paint   mBitmapPaint;
    
    private Paint xuxianPaint;
    /**
     *左边空距
     */
    private int marginLeft=10;
    private int marginTop=20;
    
    NumberFormat numberformat=new DecimalFormat("#.##");
	NumberFormat Intformat=new DecimalFormat("#");
    private CurveObj curveObj;
//	
    private int canvasWeight;
    private int canvasHeight;
    public DrawCurveView(Context context,AttributeSet attrs) {
    	super(context,attrs);
    	setOnTouchListener(this);
		setFocusable(true);
		setLongClickable(true);
    	Log.d("draw new", "init draw class====================");
//    	DisplayMetrics dm = getResources().getDisplayMetrics();
// 		screenWidth = dm.widthPixels;
// 		screenHeight = dm.heightPixels;
 		if(curvePaint==null)
 			initCurvePaint();
 		if(coordinatePaint==null)
 			initCoordinatePaint();
 		if(curveTextPaint==null)
 			initCurveTextPaint();
 		mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
//        mCanvas = new Canvas(mBitmap);
        mPath = new Path();//画线用的路径对象
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
 		
        xuxianPaint = new Paint();
        xuxianPaint.setAntiAlias(true);//
        xuxianPaint.setDither(true);
        xuxianPaint.setColor(0xFFcc0000);
        xuxianPaint.setStyle(Paint.Style.STROKE);
        //这里表示虚线的样式
         PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);
         xuxianPaint.setPathEffect(effects);
         xuxianPaint.setStrokeWidth(1);
         
         
	}

	
    

    private void initCurveTextPaint() {
    	curveTextPaint = new Paint();
    	curveTextPaint.setAntiAlias(true);
    	curveTextPaint.setDither(true); 
    	curveTextPaint.setColor(0xCCFF0000);
    	curveTextPaint.setStyle(Paint.Style.STROKE);
    	curveTextPaint.setStrokeJoin(Paint.Join.ROUND);
    	curveTextPaint.setStrokeCap(Paint.Cap.ROUND);
    	curveTextPaint.setStrokeWidth(1);//线条粗细
	}




	private void initCoordinatePaint() {
		coordinatePaint = new Paint();
		coordinatePaint.setAntiAlias(true);
		coordinatePaint.setDither(true); 
		coordinatePaint.setColor(0xffFFff00);
		coordinatePaint.setStyle(Paint.Style.STROKE);
		coordinatePaint.setStrokeJoin(Paint.Join.ROUND);
		coordinatePaint.setStrokeCap(Paint.Cap.ROUND);
		coordinatePaint.setStrokeWidth(1);//线条粗细
	}




	private void initCurvePaint() {
    	curvePaint = new Paint();
    	curvePaint.setAntiAlias(true);
    	curvePaint.setDither(true); 
    	curvePaint.setColor(0xCCFF0000);
    	curvePaint.setStyle(Paint.Style.STROKE);
    	curvePaint.setStrokeJoin(Paint.Join.ROUND);
    	curvePaint.setStrokeCap(Paint.Cap.ROUND);
    	curvePaint.setStrokeWidth(1);//线条粗细
	}




	public void setFx(float[] fx) {
		this.fx = fx;
	}

	public void setFy(float[] fy) {
		this.fy = fy;
	}

	public float[] getFx() {
		return fx;
	}

	public float[] getFy() {
		return fy;
	}

//	@Override
//    protected void onDraw(Canvas canvas) {
//		Log.d("DrawView", "------------ondraw2----------");
//        canvas.drawColor(0xFFAAAAAA);
//	}
	private float rationf=0.1f;
    protected void onDraw(Canvas canvas) {
    	
    	Log.d("DrawView", "------------ondraw----------");
    	canvas.drawColor(R.color.transparent);// 设置为透明
        canvas.drawColor(0xFFAAAAAA);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
       
        /**
         * 计算x,y坐标分割点数值
         */
        calculateXYPoint();
        /**
         * 绘制XY坐标
         */
        drawXy();
      canvas.drawLine(marginLeft,0, marginLeft,220, coordinatePaint);
      canvas.drawLine(marginLeft-5,200,310,200, coordinatePaint);
        Log.d("DrawView", "------------ondraw---2-------");
        if(fx!=null&&fx.length>0){
        	Log.d("DrawView", "------------ondraw----3------");
	        float[] datax=new float[fx.length];
	        float[] datay=new float[fy.length];
	        /**
	         * 计算数据在实际界面中的xy轴坐标
	         */
	        Log.d("calculateDateXY===","----");
	        calculateDateXY(datax,datay);
	        /**
	         * 绘制数据点
	         */
	        Log.d("drawDateXY===","----");
            for (int i = 0; i < datax.length-1; i++) {
    		canvas.drawLine(datax[i],datay[i], datax[i+1],datay[i+1], coordinatePaint);
    		//canvas.drawText(perXsText[i], perXs[i],210, coordinatePaint);
		}
            //drawDateXY(datax,datay);//这里让path对象记录要走过的路径
	        drawXY(canvas);//这里画虚线和坐标轴
        }
       // canvas.drawPath(mPath, curvePaint);//这里是把path对象记录的数据画出来
        if (curveObj!=null) {
            Log.d("DrawCurveView_curveObj","curveObj title:"+curveObj.getTitle());
            canvas.drawText(curveObj.getTitle(),150,200,curvePaint);
        }else{
            Log.d("DrawCurveView_curveObj","curveObj is null");
        }
        canvasWeight=canvas.getWidth();
        canvasHeight=canvas.getHeight();
        Log.d("DrawCurveView_curveObj", "ondraw:canvasWeight:"+canvasWeight+"|canvasHeight:"+canvasHeight);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        //canvas.scale(0.5f,0.5f);
        
//        canvas.drawPath(mPath, mPaint);
        
//        canvas.drawLine(0,0, 0,300, mPaint);
//        canvas.drawLine(0,200,320,200, mPaint);
//        
//        canvas.drawLine(0,50,10,50, mPaint2);
//        canvas.drawText("150", 12, 50, mPaint);
//        
//        canvas.drawLine(0,100,10,100, mPaint2);
//        canvas.drawText("100", 12, 100, mPaint);
//        
//        canvas.drawLine(0,150,10,150, mPaint2);
//        canvas.drawText("50", 12,150, mPaint);
//        canvas.drawLine(0,150,320,150, mPaint2);
//        
//        
//        canvas.drawLine(0,180,10,180, mPaint2);
//        canvas.drawText("20", 12, 180, mPaint);
//        
//        //
//        canvas.drawLine(10,200,10,190, mPaint2);
//        canvas.drawText("10", 4, 210, mPaint);
//        
//        canvas.drawLine(20,200,20,190, mPaint2);
//        canvas.drawText("20", 20, 210, mPaint);
//        
//        canvas.drawLine(40,200,40,0, mPaint2);
//        canvas.drawText("40", 40, 210, mPaint);
//        
//        canvas.drawLine(60,200,60,190, mPaint2);
//        canvas.drawText("60", 60, 210, mPaint);
//        
//        canvas.drawLine(100,0,100,200, mPaint2);
//        canvas.drawLine(100,200,100,190, mPaint2);
//        canvas.drawText("100", 100, 210, mPaint);
//        
//        canvas.drawLine(200,200,200,190, mPaint2);
//        canvas.drawText("200", 200, 210, mPaint);
      
    }
    /**
     * 计算数据在实际界面中的xy轴坐标
     * 这里我们默认函数为递增函数。方便取得数据最大最小值
     * 
     * x计算公式为：
     * self-min
     * -------- *300+a(a为常量，即第一个坐标x与原点的距离，这里暂定为30,如果有原点，则去掉a)
     * max-min
     * 
     * 
     */
    private void calculateDateXY(float[] datax, float[] datay) {
    	
			//取得x轴y轴最大最小值
			float minx=fx[0];
			float maxx=fx[fx.length-1];
			float miny=fy[0];
			float maxy=fy[fy.length-1];
			

			boolean hasYuandian=false;
			if(minx==0)
				hasYuandian=true;
			float disX=marginLeft;//与界面边距
			float disy=marginTop;
			if(!hasYuandian)//如果需要设置离原点距离
				disX+=10;
			
			//画10个XY坐标点。
			//TODO,暂未处理，目前坐标数量为数据数组值
			int perX=Integer.parseInt(Intformat.format((maxx-minx)/6));//计算坐标间隔
			perXs=new float[fx.length];
			perXsText=new String[fx.length];
			for (int i = 0; i < fx.length; i++) {
				if(i==0){
					perXs[i]=fx[i];
					//perXsText[i]=String.valueOf(perXs[i]);
				}
				else{
					perXs[i]=perXs[i-1]+perX;
					}
				perXsText[i]=String.valueOf(perXs[i]);
				Log.d("text", "p=="+i+"/"+perXsText[i]);
			}
			for (int i = 0; i < perXs.length; i++) {
				double d=(perXs[i]-minx)*300/(maxx-minx);
				d+=disX;
				float da=Float.parseFloat(numberformat.format(d));
				perXs[i]=da;
			}
			
			
			int perY=Integer.parseInt(Intformat.format((maxy-miny)/4));//计算坐标间隔
			perYs=new float[fy.length];
			perYsText=new String[fy.length];
			for (int i = 0; i < fy.length; i++) {
				if(i==0){
					perYs[i]=fy[i];
					//perXsText[i]=String.valueOf(perXs[i]);
				}
				else{
					perYs[i]=perYs[i-1]+perY;
					}
				perYsText[i]=String.valueOf(Integer.parseInt(Intformat.format(perYs[i])));
				Log.d("textY", "p=="+i+"/"+perYsText[i]);
			}
			for (int i = 0; i < perYs.length; i++) {
				double d=(perYs[i]-miny)*150/(maxy-miny);
				d+=disy;
				float da=Float.parseFloat(numberformat.format(d));
				perYs[i]=(150+2*disy)-da;
			}
			
			
			//计算界面间隔值
			for (int i = 0; i < fx.length; i++) {
				double d=(fx[i]-minx)*300/(maxx-minx);
				d+=disX;
				float da=Float.parseFloat(numberformat.format(d));
				datax[i]=da;
			}
			
			for (int i = 0; i < fy.length; i++) {
				double d=(fy[i]-miny)*150/(maxy-miny);
				d+=disy;
				float da=Float.parseFloat(numberformat.format(d));
				datay[i]=(150+2*disy)-da;//垂直翻转
			}
	}



    private void drawXY(Canvas canvas) {
    	for (int i = 0; i < perXs.length; i++) {
    		canvas.drawLine(perXs[i],0, perXs[i],200, xuxianPaint);
    		canvas.drawText(perXsText[i], perXs[i],210, coordinatePaint);
		}
    	for (int i = 0; i < perYs.length; i++) {
    		if(i<5){
    		canvas.drawLine(310,perYs[i], marginLeft,perYs[i], xuxianPaint);
    		canvas.drawText(perYsText[i], marginLeft,perYs[i], coordinatePaint);
    		}
		}
	}




	/**
     * 绘制XY坐标
     */
	private void drawXy() {
		Log.d("DrawView", "------------ondraw----drawXy------");
	}

	 /**
     * 计算x,y坐标分割点数值
     */
	private void calculateXYPoint() {
		Log.d("DrawView", "------------ondraw---calculateXYPoint-------");
	}



	 /**
     * 绘制数据点
     */
	private void drawDateXY(float[] datax, float[] datay) {
		Log.d("draw begin---", "-----------------------draw begin------------"+datax.length);
    	 for (int i = 0; i < datax.length; i++) {
 			if(i==0){
 				touch_start(datax[i], datay[i]);
// 				invalidate();
 			}else{
 				touch_move(datax[i], datay[i]);
// 				invalidate();
 			}
 		}
	}


	private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;
    
    private void touch_start(float x, float y) {
//        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }
    private void touch_move(float x, float y) {
    	Log.d("draw===x,y==", String.valueOf(x)+"|"+String.valueOf(y));
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;
        }
    }
//    private void touch_up() {
//        mPath.lineTo(mX, mY);
//        // commit the path to our offscreen
//        mCanvas.drawPath(mPath, curvePaint);
//        // kill this so we don't double draw
//        mPath.reset();
//    }
 // 屏幕宽高
	private int display_w;
	private int display_h;
    int lastx = 0;
	int lasty = 0;
	private int left = 0;
	private int top = 0;
    public boolean onTouch(View v, MotionEvent event) {
    	 
         Log.d("DrawCurveView_curveObj", "onTouch:canvasWeight:"+canvasWeight+"|canvasHeight:"+canvasHeight);
		int dx;
		int dy;

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			lastx = (int) event.getRawX();
			lasty = (int) event.getRawY();
			break;
		case MotionEvent.ACTION_MOVE:
			if(rationf>0.5f){
				rationf=rationf-0.1f;
			}
			if(rationf<=0.1f){
				rationf=rationf+0.1f;
			}
			invalidate();
			/*if (canvasWeight > display_w || canvasHeight > display_h) {
				dx = (int) event.getRawX() - lastx;
				dy = (int) event.getRawY() - lasty;
				Log.i("onScroll", "onScrollonScroll" + dx);
				Log.i("onScroll", "onScrollonScroll" + dy);

				left = left - dx;
				top = top - dy;
				
				if (left < 0) {
					left = 0;
				}
				if (canvasWeight > display_w && left > canvasWeight - display_w) {
					left = canvasWeight - display_w;
				}
				if (top < 0) {
					top = 0;
				}
				if (canvasHeight > display_h && top > canvasHeight - display_h) {
					top = canvasHeight - display_h;
				}
				invalidate();
				
				lastx = (int) event.getRawX();
				lasty = (int) event.getRawY();
			}*/
			break;
		default:
			break;
		}

		return false;
	}
    
    


    public CurveObj getCurveObj() {
        return curveObj;
    }

    public void setCurveObj(CurveObj curveObj) {
        this.curveObj = curveObj;
    }




	public Bitmap getmBitmap() {
		return mBitmap;
	}
    
    
}
